{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Fiducial Points Estimation using TAO FPENet\n",
    "\n",
    "Transfer learning is the process of transferring learned features from one application to another. It is a commonly used training technique where you use a model trained on one task and re-train to use it on a different task. \n",
    "\n",
    "Train Adapt Optimize (TAO) Toolkit is a simple and easy-to-use Python based AI toolkit for taking purpose-built AI models and customizing them with users' own data.\n",
    "\n",
    "<img align=\"center\" src=\"https://d29g4g2dyqv443.cloudfront.net/sites/default/files/akamai/TAO/tlt-tao-toolkit-bring-your-own-model-diagram.png\" width=\"1080\">\n",
    "\n",
    "## Sample output predictions from a FPENet model\n",
    "\n",
    "<img align=\"center\" src=\"https://docscontent.nvidia.com/dims4/default/b677267/2147483647/strip/true/crop/1200x1069+0+0/resize/2400x2138!/format/webp/quality/90/?url=https%3A%2F%2Fk3-prod-nvidia-docs.s3.amazonaws.com%2Fbrightspot%2Fsphinx%2F00000187-579f-dfeb-adf7-77df80550000%2Ftao%2Ftao-toolkit%2F_images%2Ffpe_sample_keypoints.png\" width=\"1080\">"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Learning Objectives\n",
    "In this notebook, you will learn how to leverage the simplicity and convenience of TAO to:\n",
    "\n",
    "* Take a pretrained model and train a FPENet model on AFW dataset\n",
    "* Run Inference on the trained model\n",
    "* Export the retrained model to a .onnx file for deployment to DeepStream SDK\n",
    "\n",
    "At the end of this notebook, you will have generated a trained and optimized `FPENet` model, \n",
    "which you may deploy via [DeepStream](https://developer.nvidia.com/deepstream-sdk).\n",
    "\n",
    "### Table of Contents\n",
    "\n",
    "This notebook shows an example of Fiducial Points Estimation using Train Adapt Optimize (TAO) Toolkit.\n",
    "\n",
    "0. [Set up env variables, map drives, and install dependencies](#head-0)\n",
    "1. [Install the TAO Launcher](#head-1)\n",
    "2. [Prepare dataset and pre-trained model](#head-2) <br>\n",
    "    2.1 [Verify downloaded dataset](#head-2-1) <br>\n",
    "    2.2 [Download pre-trained model](#head-2-2) <br>\n",
    "3. [Generate tfrecords from labels in json format](#head-3)\n",
    "4. [Provide training specification](#head-4)\n",
    "5. [Run TAO training](#head-5)\n",
    "6. [Evaluate trained models](#head-6)\n",
    "7. [Run inference for a set of images](#head-7)\n",
    "8. [Deploy](#head-8)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 0. Set up env variables, map drives, and install dependencies <a class=\"anchor\" id=\"head-0\"></a>\n",
    "When using the purpose-built pretrained models from NGC, please make sure to set the `$KEY` environment variable to the key as mentioned in the model overview. Failing to do so, can lead to errors when trying to load them as pretrained models.\n",
    "\n",
    "The following notebook requires the user to set an env variable called the `$LOCAL_PROJECT_DIR` as the path to the users' workspace. Please note that the dataset to run this notebook is expected to reside in the `$LOCAL_PROJECT_DIR/fpenet/data`, while the TAO experiment generated collaterals will be output to `$LOCAL_PROJECT_DIR/fpenet`. More information on how to set up the dataset and the supported steps in the TAO workflow are provided in the subsequent cells.\n",
    "\n",
    "*Note: This notebook currently is by default set up to run training using 1 GPU. To use more GPU's please update the env variable `$NUM_GPUS` accordingly*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setting up env variables for cleaner command-line commands.\n",
    "import os\n",
    "\n",
    "%env KEY=nvidia_tlt\n",
    "%env NUM_GPUS=1\n",
    "%env USER_EXPERIMENT_DIR=/workspace/tao-experiments/fpenet\n",
    "%env DATA_DIR=/workspace/tao-experiments/fpenet/data\n",
    "\n",
    "# The number of keypoints can be chosen from [10, 80] for this notebook\n",
    "%env NUM_KEYPOINTS=80\n",
    "\n",
    "# Set this path if you don't run the notebook from the samples directory.\n",
    "# %env NOTEBOOK_ROOT=~/tao-samples/fpenet\n",
    "\n",
    "# Please define this local project directory that needs to be mapped to the TAO docker session.\n",
    "# !PLEASE MAKE SURE TO UPDATE THIS PATH!.\n",
    "%env LOCAL_PROJECT_DIR=/path/to/local/experiments\n",
    "\n",
    "# $SAMPLES_DIR is the path to the sample notebook folder and the dependency folder\n",
    "# $SAMPLES_DIR/deps should exist for dependency installation\n",
    "%env SAMPLES_DIR=/path/to/local/samples_dir\n",
    "\n",
    "os.environ[\"LOCAL_DATA_DIR\"] = os.path.join(\n",
    "    os.getenv(\"LOCAL_PROJECT_DIR\", os.getcwd()),\n",
    "    \"fpenet/data\"\n",
    ")\n",
    "os.environ[\"LOCAL_EXPERIMENT_DIR\"] = os.path.join(\n",
    "    os.getenv(\"LOCAL_PROJECT_DIR\", os.getcwd()),\n",
    "    \"fpenet\"\n",
    ")\n",
    "\n",
    "# The sample spec files are present in the same path as the downloaded samples.\n",
    "os.environ[\"LOCAL_SPECS_DIR\"] = os.path.join(\n",
    "    os.getenv(\"NOTEBOOK_ROOT\", os.getcwd()),\n",
    "    \"specs\"\n",
    ")\n",
    "%env SPECS_DIR=/workspace/tao-experiments/fpenet/specs\n",
    "%env PROJECT_DIR=/workspace/tao-experiments\n",
    "\n",
    "# Showing list of specification files.\n",
    "!ls -rlt $LOCAL_SPECS_DIR"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The cell below maps the project directory on your local host to a workspace directory in the TAO docker instance, so that the data and the results are mapped from in and out of the docker. For more information please refer to the [launcher instance](https://docs.nvidia.com/tao/tao-toolkit/text/tao_launcher.html) in the user guide.\n",
    "\n",
    "When running this cell on AWS, update the drive_map entry with the dictionary defined below, so that you don't have permission issues when writing data into folders created by the TAO docker.\n",
    "\n",
    "```json\n",
    "drive_map = {\n",
    "    \"Mounts\": [\n",
    "            # Mapping the data directory\n",
    "            {\n",
    "                \"source\": os.environ[\"LOCAL_PROJECT_DIR\"],\n",
    "                \"destination\": \"/workspace/tao-experiments\"\n",
    "            },\n",
    "            # Mapping the specs directory.\n",
    "            {\n",
    "                \"source\": os.environ[\"LOCAL_SPECS_DIR\"],\n",
    "                \"destination\": os.environ[\"SPECS_DIR\"]\n",
    "            },\n",
    "            # Mapping data\n",
    "            {\n",
    "                \"source\": os.environ[\"LOCAL_DATA_DIR\"],\n",
    "                \"destination\": os.environ[\"DATA_DIR\"]\n",
    "            },\n",
    "        ],\n",
    "    \"DockerOptions\": {\n",
    "        \"user\": \"{}:{}\".format(os.getuid(), os.getgid())\n",
    "    }\n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Mapping up the local directories to the TAO docker.\n",
    "import json\n",
    "mounts_file = os.path.expanduser(\"~/.tao_mounts.json\")\n",
    "\n",
    "# Define the dictionary with the mapped drives\n",
    "drive_map = {\n",
    "    \"Mounts\": [\n",
    "        # Mapping the data directory\n",
    "        {\n",
    "            \"source\": os.environ[\"LOCAL_PROJECT_DIR\"],\n",
    "            \"destination\": os.environ[\"PROJECT_DIR\"]\n",
    "        },\n",
    "        # Mapping the specs directory.\n",
    "        {\n",
    "            \"source\": os.environ[\"LOCAL_SPECS_DIR\"],\n",
    "            \"destination\": os.environ[\"SPECS_DIR\"]\n",
    "        },\n",
    "        # Mapping data\n",
    "        {\n",
    "            \"source\": os.environ[\"LOCAL_DATA_DIR\"],\n",
    "            \"destination\": os.environ[\"DATA_DIR\"]\n",
    "        },\n",
    "    ]\n",
    "}\n",
    "\n",
    "# Writing the mounts file.\n",
    "with open(mounts_file, \"w\") as mfile:\n",
    "    json.dump(drive_map, mfile, indent=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat ~/.tao_mounts.json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install requirement\n",
    "!pip3 install Cython==0.29.36\n",
    "!pip3 install -r $SAMPLES_DIR/deps/requirements-pip.txt"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Install the TAO launcher <a class=\"anchor\" id=\"head-1\"></a>\n",
    "The TAO launcher is a python package distributed as a python wheel listed in PyPI. You may install the launcher by executing the following cell.\n",
    "\n",
    "Please note that TAO Toolkit recommends users run the TAO launcher in a virtual env with python 3.6.9. You may follow the instruction on this [page](https://virtualenvwrapper.readthedocs.io/en/latest/install.html) to set up a python virtual env using the `virtualenv` and `virtualenvwrapper` packages. Once you have set up virtualenvwrapper, please set the version of python to be used in the virtual env by using the `VIRTUALENVWRAPPER_PYTHON` variable. You may do so by running\n",
    "\n",
    "```sh\n",
    "export VIRTUALENVWRAPPER_PYTHON=/path/to/bin/python3.x\n",
    "```\n",
    "where x >= 6 and <= 8\n",
    "\n",
    "We recommend performing this step first and then launching the notebook from the virtual environment. In addition to installing TAO python package, please make sure of the following software requirements:\n",
    "* python >=3.7, <=3.10.x\n",
    "* docker-ce > 19.03.5\n",
    "* docker-API 1.40\n",
    "* nvidia-container-toolkit > 1.3.0-1\n",
    "* nvidia-container-runtime > 3.4.0-1\n",
    "* nvidia-docker2 > 2.5.0-1\n",
    "* nvidia-driver > 455+\n",
    "\n",
    "Once you have installed the pre-requisites, please log in to the docker registry nvcr.io by following the command below\n",
    "\n",
    "```sh\n",
    "docker login nvcr.io\n",
    "```\n",
    "\n",
    "You will be triggered to enter a username and password. The username is `$oauthtoken` and the password is the API key generated from `ngc.nvidia.com`. Please follow the instructions in the [NGC setup guide](https://docs.nvidia.com/ngc/ngc-overview/index.html#generating-api-key) to generate your own API key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Skip this step if you have already installed the TAO launcher.\n",
    "!pip3 install nvidia-tao"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View the versions of the TAO launcher\n",
    "!tao info"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Prepare dataset and pre-trained model <a class=\"anchor\" id=\"head-2\"></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Download public dataset.\n",
    "\n",
    "Please download and unzip the AFW dataset to `$LOCAL_EXPERIMENT_DIR` directory.\n",
    "\n",
    "https://ibug.doc.ic.ac.uk/download/annotations/afw.zip/"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A. Download and Verify dataset <a class=\"anchor\" id=\"head-2-1\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check the dataset is present\n",
    "!if [ ! -d $LOCAL_EXPERIMENT_DIR/afw ]; then echo 'Data folder not found, please download.'; else echo 'Found Data folder.';fi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# convert datset to required format\n",
    "import os\n",
    "from data_utils import convert_dataset\n",
    "afw_data_path = os.path.join(os.environ[\"LOCAL_EXPERIMENT_DIR\"], 'afw')\n",
    "afw_image_save_path = os.path.join(os.environ[\"USER_EXPERIMENT_DIR\"], 'afw')\n",
    "num_keypoints = int(os.environ[\"NUM_KEYPOINTS\"])\n",
    "if num_keypoints == 80:\n",
    "    output_json_path = os.path.join(os.environ['LOCAL_DATA_DIR'], 'afw/afw.json')\n",
    "    %env DATASET_ID=afw\n",
    "elif num_keypoints == 10:\n",
    "    output_json_path = os.path.join(os.environ['LOCAL_DATA_DIR'], 'afw_10/afw_10.json')\n",
    "    %env DATASET_ID=afw_10\n",
    "\n",
    "convert_dataset(afw_data_path, output_json_path, afw_image_save_path, num_keypoints)\n",
    "# Note that we are using dummy labels for keypoints 69 to 80 if the NUM_KEYPOINTS=80.\n",
    "\n",
    "print('Dataset conversion finished.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check the dataset is generated\n",
    "!if [ ! -f $LOCAL_DATA_DIR/$DATASET_ID/${DATASET_ID}.json ]; then echo 'Labels not found, please regenerate.'; else echo 'Found Labels.';fi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sample json label.\n",
    "!sed -n 1,201p $LOCAL_DATA_DIR/$DATASET_ID/${DATASET_ID}.json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sample image.\n",
    "import os\n",
    "from IPython.display import Image\n",
    "Image(filename=os.path.join(afw_data_path, '134212_1.png'))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### B. Obtain pre-trained model <a class=\"anchor\" id=\"head-2-2\"></a>\n",
    "\n",
    "Please follow the instructions in the following to download and verify the pretrain model for fpenet.\n",
    "\n",
    "For FpeNet pre-trained model please download model: `nvidia/tao/fpenet:trainable_v1.0`.\n",
    "\n",
    "After obtaining the pre-trained model, please place the model in $LOCAL_EXPERIMENT_DIR\n",
    "\n",
    "You will then have the following path-\n",
    "\n",
    "* pre-trained model in `$LOCAL_EXPERIMENT_DIR/pretrained_models/fpenet_vtrainable_v1.0/model.tlt`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Installing NGC CLI on the local machine.\n",
    "## Download and install\n",
    "%env CLI=ngccli_cat_linux.zip\n",
    "!mkdir -p $LOCAL_PROJECT_DIR/ngccli\n",
    "\n",
    "# Remove any previously existing CLI installations\n",
    "!rm -rf $LOCAL_PROJECT_DIR/ngccli/*\n",
    "!wget \"https://ngc.nvidia.com/downloads/$CLI\" -P $LOCAL_PROJECT_DIR/ngccli\n",
    "!unzip -u \"$LOCAL_PROJECT_DIR/ngccli/$CLI\" -d $LOCAL_PROJECT_DIR/ngccli/\n",
    "!rm $LOCAL_PROJECT_DIR/ngccli/*.zip \n",
    "os.environ[\"PATH\"]=\"{}/ngccli/ngc-cli:{}\".format(os.getenv(\"LOCAL_PROJECT_DIR\", \"\"), os.getenv(\"PATH\", \"\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# List models available in the model registry.\n",
    "!ngc registry model list nvidia/tao/fpenet:*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the target destination to download the model.\n",
    "!mkdir -p $LOCAL_EXPERIMENT_DIR/pretrained_models/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download the pretrained model from NGC\n",
    "!ngc registry model download-version nvidia/tao/fpenet:trainable_v1.0 \\\n",
    "    --dest $LOCAL_EXPERIMENT_DIR/pretrained_models/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls -rlt $LOCAL_EXPERIMENT_DIR/pretrained_models/fpenet_vtrainable_v1.0 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check the model is present\n",
    "!if [ ! -f $LOCAL_EXPERIMENT_DIR/pretrained_models/fpenet_vtrainable_v1.0/model.tlt ]; then echo 'Pretrained model file not found, please download.'; else echo 'Found Pretrain model file.';fi"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Generate tfrecords from labels in json format <a class=\"anchor\" id=\"head-3\"></a>\n",
    "* Create the tfrecords using the dataset_convert command\n",
    "* Input is ground truth landmarks and output is tfrecord files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Modify dataset_config for data preparation\n",
    "# verify all paths\n",
    "num_keypoints = int(os.environ[\"NUM_KEYPOINTS\"])\n",
    "if num_keypoints==80:\n",
    "    %env DATASET_CONFIG=dataset_config.yaml\n",
    "elif num_keypoints==10:\n",
    "    %env DATASET_CONFIG=dataset_config_10.yaml\n",
    "else:\n",
    "    print(\"No dataset config for \", num_keypoints)\n",
    "!cat $LOCAL_SPECS_DIR/$DATASET_CONFIG"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls $LOCAL_DATA_DIR/$DATASET_ID"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model fpenet dataset_convert -e $SPECS_DIR/$DATASET_CONFIG -r $USER_EXPERIMENT_DIR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the tfrecords are generated\n",
    "!if [ ! -d $LOCAL_EXPERIMENT_DIR/data/tfrecords/$DATASET_ID/FpeTfRecords ]; then echo 'Tfrecords folder not found, please generate.'; else echo 'Found Tfrecords folder.';fi"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Provide training specification <a class=\"anchor\" id=\"head-4\"></a>\n",
    "* Tfrecords for the train datasets\n",
    "    * In order to use the newly generated tfrecords for training, update the 'tfrecords_directory_path' and 'tfrecord_folder_name' parameters of 'dataset_info' section in the spec file at `$SPECS_DIR/experiment_spec.yaml`\n",
    "* Pre-trained model path\n",
    "    * Update \"pretrained_model_path\" in the spec file at `$SPECS_DIR/experiment_spec.yaml`\n",
    "    * If you want to train from random weights with your own data, you can enter \"null\" for \"pretrained_model_path\" section\n",
    "* Augmentation parameters for on the fly data augmentation\n",
    "* Other training (hyper-)parameters such as batch size, number of epochs, learning rate etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_keypoints = int(os.environ[\"NUM_KEYPOINTS\"])\n",
    "if num_keypoints==80:\n",
    "    %env EXPERIMENT_SPEC=experiment_spec.yaml\n",
    "elif num_keypoints==10:\n",
    "    %env EXPERIMENT_SPEC=experiment_spec_10.yaml\n",
    "else:\n",
    "    print(\"No experiment spec for \", num_keypoints)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat $LOCAL_SPECS_DIR/$EXPERIMENT_SPEC"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Run TAO training <a class=\"anchor\" id=\"head-5\"></a>\n",
    "* Provide the sample spec file and the output directory location for models\n",
    "\n",
    "*Note: The training may take hours to complete. Also, the remaining notebook, assumes that the training was done in single-GPU mode. \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model fpenet train -e $SPECS_DIR/$EXPERIMENT_SPEC \\\n",
    "                  -r $USER_EXPERIMENT_DIR/models/exp1 \\\n",
    "                  -k $KEY \\\n",
    "                  --gpus $NUM_GPUS"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the training folder for generated files\n",
    "!ls -lh $LOCAL_EXPERIMENT_DIR/models/exp1"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Evaluate the trained model <a class=\"anchor\" id=\"head-6\"></a>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model fpenet evaluate  -m $USER_EXPERIMENT_DIR/models/exp1 \\\n",
    "                      -k $KEY \\\n",
    "                      -r $USER_EXPERIMENT_DIR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the kpi predictions file is generated\n",
    "!if [ ! -f $LOCAL_EXPERIMENT_DIR/models/exp1/kpi_testing_error_per_region.csv ]; then echo 'KPI results file not found!'; else cat $LOCAL_EXPERIMENT_DIR/models/exp1/kpi_testing_error_per_region.csv;fi\n",
    "# Since keypoints 69 to 80 are dummy labels, error for pupil and ears would be high."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Run inference on testing set <a class=\"anchor\" id=\"head-7\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model fpenet inference -e $SPECS_DIR/$EXPERIMENT_SPEC \\\n",
    "                      -i $SPECS_DIR/inference_sample.json \\\n",
    "                      -k $KEY \\\n",
    "                      -r $LOCAL_PROJECT_DIR \\\n",
    "                      -m $USER_EXPERIMENT_DIR/models/exp1/model.hdf5 \\\n",
    "                      -o $USER_EXPERIMENT_DIR/models/exp1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the results file is generated\n",
    "!if [ ! -f $LOCAL_EXPERIMENT_DIR/models/exp1/result.txt ]; then echo 'Results file not found!'; else cat $LOCAL_EXPERIMENT_DIR/models/exp1/result.txt;fi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import cv2\n",
    "import IPython.display\n",
    "import PIL.Image\n",
    "%matplotlib inline\n",
    "num_keypoints = int(os.environ[\"NUM_KEYPOINTS\"])\n",
    "if num_keypoints == 80: # not drawing ear points if NUM_KEYPOINTS=80\n",
    "    num_keypoints=76\n",
    "# read results\n",
    "results_file = os.path.join(os.environ['LOCAL_EXPERIMENT_DIR'], 'models/exp1/result.txt')\n",
    "results = open(results_file, 'r').readlines()[0] # display one image as an example\n",
    "\n",
    "pred_part = results.strip().split(' ')\n",
    "# get image path (append root path, if present)\n",
    "image_path = pred_part[0].replace(os.environ[\"USER_EXPERIMENT_DIR\"], os.environ[\"LOCAL_EXPERIMENT_DIR\"])\n",
    "# get predictions\n",
    "fl_res = [float(x) for x in pred_part[1:]]\n",
    "# read image\n",
    "img = cv2.imread(image_path)\n",
    "img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
    "# set color for landmarks\n",
    "fl_color=(0,255,0)\n",
    "# loop through keypoints and draw on image\n",
    "for q in range(num_keypoints): # not drawing ear points if NUM_KEYPOINTS=80\n",
    "    row_pred_x = fl_res[2*q]\n",
    "    col_pred_y = fl_res[(2*q)+1]\n",
    "    img_rgb = cv2.circle(img_rgb,(int(row_pred_x), int(col_pred_y)), 1, fl_color, 1)\n",
    "# display image\n",
    "IPython.display.display(PIL.Image.fromarray(img_rgb))\n",
    "# Note that the accuracy is not gauranteed for this visualization example."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Deploy / Export <a class=\"anchor\" id=\"head-8\"></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.1 Export .onnx model\n",
    "\n",
    "Use the export functionality to export an onnx model in fp32 format without any optimizations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model fpenet export -m $USER_EXPERIMENT_DIR/models/exp1/model.hdf5 \\\n",
    "                   -r $USER_EXPERIMENT_DIR \\\n",
    "                   -k $KEY \\\n",
    "                   --backend onnx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the deployment file is presented\n",
    "!if [ ! -f $LOCAL_EXPERIMENT_DIR/models/exp1/model.onnx ]; then echo 'Deployment file not found, please generate.'; else echo 'Found deployment file.';fi"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.2 INT8 Optimization"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FPENet model supports int8 inference mode in TensorRT. In order to do this, the model is first calibrated to run 8-bit inferences. This is the process:\n",
    "\n",
    "* Provide a directory with set of images to be used for calibration.\n",
    "* A calibration tensorfile is generated and saved in --cal_data_file\n",
    "* This tensorfile is used to calibrate the model and the calibration table is stored in --cal_cache_file\n",
    "* The calibration table in addition to the model is used to generate the int8 tensorrt engine to the path --engine_file\n",
    "\n",
    "*Note: For this example, we generate a calibration tensorfile containing 100 batches of training data. Ideally, it is best to use at least 10-20% of the training data to do so. The more data provided during calibration, the closer int8 inferences are to fp32 inferences.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Number of calibration samples to use\n",
    "%set_env NUM_CALIB_SAMPLES=100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python3 sample_calibration_images.py \\\n",
    "    -a $LOCAL_DATA_DIR/$DATASET_ID/${DATASET_ID}.json \\\n",
    "    -oi $USER_EXPERIMENT_DIR \\\n",
    "    -ni $LOCAL_EXPERIMENT_DIR \\\n",
    "    -o $LOCAL_EXPERIMENT_DIR/data/calibration_samples/ \\\n",
    "    -n $NUM_CALIB_SAMPLES \\\n",
    "    --num_keypoints $NUM_KEYPOINTS \\\n",
    "    --randomize"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.3 Export Deployable INT8 Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model fpenet export -m $USER_EXPERIMENT_DIR/models/exp1/model.hdf5 \\\n",
    "                   -r $LOCAL_PROJECT_DIR \\\n",
    "                   -k $KEY \\\n",
    "                   --engine_file $USER_EXPERIMENT_DIR/models/exp1/model.int8.engine \\\n",
    "                   --data_type int8 \\\n",
    "                   --cal_image_dir $LOCAL_EXPERIMENT_DIR/data/calibration_samples/ \\\n",
    "                   --cal_cache_file $USER_EXPERIMENT_DIR/models/exp1/int8_calibration.bin \\\n",
    "                   --cal_data_file $USER_EXPERIMENT_DIR/models/exp1/int8_calibration.tensorfile \\\n",
    "                   --batches 100 \\\n",
    "                   --backend onnx"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.4 Run Inference on Exported INT8 Engine File"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model fpenet inference -e $SPECS_DIR/$EXPERIMENT_SPEC \\\n",
    "                      -i $SPECS_DIR/inference_sample.json \\\n",
    "                      -r $USER_EXPERIMENT_DIR \\\n",
    "                      -k $KEY \\\n",
    "                      -m $USER_EXPERIMENT_DIR/models/exp1/model.int8.engine \\\n",
    "                      -o $USER_EXPERIMENT_DIR/models/exp1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the results file is generated\n",
    "!if [ ! -f $LOCAL_EXPERIMENT_DIR/models/exp1/result.txt ]; then echo 'Results file not found!'; else cat $LOCAL_EXPERIMENT_DIR/models/exp1/result.txt;fi"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
